package busterminalweb.action.route;

import busterminal.entity.Route;
import busterminal.entity.RouteImplementation;
import busterminal.entity.StoppingPoint;
import busterminal.entity.StoppingPointImplementation;
import busterminal.entity.service.RouteType;
import busterminal.exception.BusinessException;
import busterminal.persistence.RouteDAO;
import busterminal.services.ServiceLocator;
import busterminalweb.action.Action;
import busterminalweb.action.ActionResult;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Сохранить маршрут
 */
public class SaveRouteAction implements Action {

    /**
     * Выполнить действие
     * @param request запрос
     * @param response ответ
     * @return страница, которой нужно передать управление
     */
    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        // if Save button have been pressed
        if (request.getParameter("saveButton") != null) {
            RouteDAO routeDAO = ServiceLocator.getService(RouteDAO.class);
            int id = Integer.parseInt(request.getParameter("id"));
            Route route = (id == 0) ? new RouteImplementation() : routeDAO.read(id);

            // load data from request
            if (request.getParameter("routeNumber") != null && !request.getParameter("routeNumber").isEmpty()) {
                route.setRouteNumber(request.getParameter("routeNumber"));
            } else {
                throw new BusinessException("Route number should be not empty");
            }
            if (request.getParameter("routeName") != null && !request.getParameter("routeName").isEmpty()) {
                route.setRouteName(request.getParameter("routeName"));
            } else {
                throw new BusinessException("Route name should be not empty");
            }
            if (request.getParameter("startPoint") != null && !request.getParameter("startPoint").isEmpty()) {
                StoppingPoint startStoppingPoint = new StoppingPointImplementation();
                startStoppingPoint.setId(Integer.parseInt(request.getParameter("startPoint")));
                route.setStartPoint(startStoppingPoint);
            } else {
                throw new BusinessException("It is necessary to define start stopping point");
            }
            if (request.getParameter("endPoint") != null && !request.getParameter("endPoint").isEmpty()) {
                StoppingPoint endStoppingPoint = new StoppingPointImplementation();
                endStoppingPoint.setId(Integer.parseInt(request.getParameter("endPoint")));
                route.setEndPoint(endStoppingPoint);
            } else {
                throw new BusinessException("It is necessary to define end stopping point");
            }
            if (request.getParameterValues("intermediateStoppingPointsList") != null && !request.getParameter("intermediateStoppingPointsList").isEmpty()) {
                List<String> stoppingPoints = Arrays.asList(request.getParameterValues("intermediateStoppingPointsList"));
                ArrayList<StoppingPoint> intermediateStoppingPointList = new ArrayList<StoppingPoint>();
                for (String stoppingPoint : stoppingPoints) {
                    StoppingPoint sp = new StoppingPointImplementation();
                    sp.setId(Integer.parseInt(stoppingPoint));
                    intermediateStoppingPointList.add(sp);
                }
                route.setIntermediateStoppingPointsList(intermediateStoppingPointList);
            } else {
                throw new BusinessException("It is necessary to define intermediate stopping point(s)");
            }
            if (request.getParameter("routeType") != null && !request.getParameter("routeType").isEmpty()) {
                route.setRouteType(RouteType.valueOf(request.getParameter("routeType")));
            } else {
                throw new BusinessException("It is necessary to define route type");
            }

            if (id != 0) {
                routeDAO.update(route);
            } else {
                routeDAO.create(route);
            }
        }

        request.getSession().getServletContext().setAttribute("link", "route.list");
        
        return ActionResult.redirect("go.to");
    }

    /**
     * Получить имя действия
     * @return имя действия
     */
    @Override
    public String getName() {
        return "route.save";
    }
}
